<?php

class Default_AuthController extends SON_Controller_Action
{
	public function indexAction()
	{
		$form = new SON_Forms_Login();
		$this->view->form = $form;
		
		if($this->_request->isPost()) {
			$data = $this->_request->getPost();
			
			if($form->isValid($data)) {
				$authAdapter = $this->getAuthAdapter();
				$authAdapter->setIdentity($data["email"])
							->setCredential($data['senha']);
		
				$result = $authAdapter->authenticate();
				if($result->isValid()) {
					$auth = Zend_Auth::getInstance();
					$auth->setStorage(new Zend_Auth_Storage_Session("default"));
					$dataAuth = $authAdapter->getResultRowObject(null, 'senha');
					$dataAuth->role = 'user';
					$auth->getStorage()->write($dataAuth);
					$this->_redirect("/");
				} else {
					$this->view->error = "Usuário/Senha Inválidos";
				}
			}
		}
	}
	
	public function logoutAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		$auth = Zend_Auth::getInstance();
		$auth->setStorage(new Zend_Auth_Storage_Session("default"));
		$auth->clearIdentity();
		$this->_redirect("auth");
	}
	
	public function forgotpasswordAction()
	{
		$form = new SON_Forms_RecuperarSenha();
		$this->view->form = $form;
		
		if($this->_request->isPost()) {
			$data = $this->_request->getPost();
			
			if($form->isValid($data)) {
				$usuario = new Usuario();
				$rusuario = $usuario->findByEmail($data['email']);
				
				if ($rusuario) {
						
					$senha = substr(md5(uniqid(rand(), true)), 0, 10);
					$usuario = new Usuario(array('id' => $rusuario->getId(), 'senha' => $senha));
					$usuario->save();
				
					$view = new Zend_View();
					$view->setScriptPath(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'mailers');
					
					$mail = new Zend_Mail('utf-8');
					$mail->setBodyHtml($view->partial('senha.phtml', array('data' => array('nome' => $rusuario->getNome(), 'senha' => $senha))), 'UTF-8', Zend_Mime::ENCODING_8BIT);
					$mail->setFrom('contato@votei.net', 'Contato - Votei.Net');
					$mail->addTo($data['email'], $data['nome']);
					$mail->setSubject('Nova senha gerada - Votei.Net', 'UTF-8', Zend_Mime::ENCODING_8BIT);
					$mail->send();
					
					$this->_helper->FlashMessenger(
						array('success' => 'Senha enviada para o e-mail informado')
					);
					
					$this->_redirect('auth');
				} else {
					$this->view->error = "E-mail não cadastrado";
				}
			}
		}
	}
	
	private function getAuthAdapter()
	{
		$bootstrap = $this->getInvokeArg("bootstrap");
		$resource = $bootstrap->getPluginResource("db");
	
		$db = $resource->getDbAdapter();
	
		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
		$authAdapter->setTableName("usuario")
					->setIdentityColumn("email")
					->setCredentialColumn("senha")
					->setCredentialTreatment('SHA1(?)');
	
		return $authAdapter;
	}
}

